from flask import Flask, request, jsonify,render_template
import cv2
import numpy as np
#from utils.preprocess import Preprocessor
import sys
from pathlib import Path
sys.path.append(str(Path(__file__).parent.parent.parent))
# 改为从 backend 包绝对导入
from src.backend.utils.preprocess import Preprocessor
from models.classifier import predict

#import os
#print("当前工作目录:", os.getcwd())
#print("preprocess.py 路径:", os.path.abspath("utils/preprocess.py"))

app = Flask(__name__,template_folder="../frontend/templates")

@app.route('/')
def home():
    return render_template('upload.html')

@app.route('/classify', methods=['POST'])
def classify():
    if 'image' not in request.files:
        return jsonify({"error": "No image uploaded"}), 400
    
    # 1. 接收图片
    file = request.files['image']
    img = cv2.imdecode(np.frombuffer(file.read(), np.uint8), cv2.IMREAD_COLOR)
    
    # 2. 预处理
    processor = Preprocessor()
    processed_img = processor.apply(img, steps=['gray', 'equalize'])
    
    # 3. 分类预测
    class_name = predict(processed_img)  # 调用模型
    
    # 4. 返回结果
    return jsonify({
        "class": class_name,
        "confidence": 0.95  # 示例置信度
    })

if __name__ == '__main__':
    app.run(debug=True)